package com.atguigu.bookcity.realm;

import com.atguigu.bookcity.entity.User;
import com.atguigu.bookcity.mapper.UserRoleMapper;
import com.atguigu.bookcity.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private UserRoleMapper userRoleMapper;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证方法");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userService.getOne(wrapper);

        if (user == null)
            return null;

//        获取用户角色信息，给该用户赋予此角色的权限
        String role = userRoleMapper.getRole(user.getId());
        user.setRole(role);
        return new SimpleAuthenticationInfo(
                user,                   //令牌对象，也就是当前用户，放入之后shiro可以全局获取
                user.getPassword(),    // 密文密码
                ShiroByteSource.of(user.getSalt()),
                getName());
    }

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权方法");
        User user = (User) this.getAvailablePrincipal(principalCollection);
        if (user == null)
            return null;
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(user.getRole());
        return info;
    }
}
